package pub.digur.stream;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;

public class PublicDigur extends Digur {

	public PublicDigur(String url) {
		super(url);
	}

	public ArrayList<Status> shit() throws Exception
	{
		URL objUrl = new URL(url);
		URLConnection conn = objUrl.openConnection();
		InputStream in = conn.getInputStream();

		XMLInputFactory factory = XMLInputFactory.newInstance();
		XMLStreamReader parser = factory.createXMLStreamReader(in);
		
		ArrayList<Status> statuses = new ArrayList<Status>();
		while (parser.hasNext())
		{
			int event = parser.next();
			if (event == XMLStreamConstants.START_ELEMENT && parser.getLocalName().equals("status"))
			{
				statuses.add(nextStatus(parser));
			}
			else if (event == XMLStreamConstants.END_DOCUMENT)
			{
				in.close();
			}
		}
		
		return statuses;
	}
	
	private Status nextStatus(XMLStreamReader parser) throws Exception
	{
		Status status = new Status();		
		while (parser.hasNext())
		{
			int event = parser.next();
			if (event == XMLStreamConstants.START_ELEMENT)
			{
				if (parser.getLocalName().equals("profile_image_url"))
				{
					parser.next();
					if (parser.isCharacters())
					{
						status.profileImage = parser.getText();
						status.profileImage = status.profileImage.replace("24x24", "48x48");
					}
				}
				else if (parser.getLocalName().equals("screen_name"))
				{
					parser.next();
					if (parser.isCharacters())
					{
						status.screenName = parser.getText();
					}
				}
				else if (parser.getLocalName().equals("text"))
				{
					parser.next();
					if (parser.isCharacters())
					{
						status.text = parser.getText();
					}
				}
				else if (parser.getLocalName().equals("created_at"))
				{
					parser.next();
					if (parser.isCharacters())
					{
						status.createdDate = parser.getText();
					}
				}
			}
			else if (event == XMLStreamConstants.END_ELEMENT && parser.getLocalName().equals("status"))
			{
				break;
			}
		}
		
		return status;
	}
}
